package com.zaoke.web.component.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zaoke.web.service.push.PushService;

@Controller
@RequestMapping("/push/")
public class PushController {

	@Autowired
	private PushService pushService;

	@RequestMapping(value="push.do",method = RequestMethod.GET)
	@ResponseBody
    public Map<String, String> push(String msg, String token) {
		Map<String, String> result = new HashMap<String, String>();
		if(StringUtils.isNotBlank(msg) && StringUtils.isNotBlank(token)){
			try {
				pushService.push(new String(msg.getBytes("ISO-8859-1")), token);
				result.put("status", "0");
			} catch (JSONException e) {
				e.printStackTrace();
				result.put("status", "200004");
				result.put("msg", "设置消息格式出错");
				return result;
			} catch (CommunicationException e) {
				e.printStackTrace();
				result.put("status", "200003");
				result.put("msg", "连接苹果服务器出错");
				return result;
			} catch (KeystoreException e) {
				e.printStackTrace();
				result.put("status", "200002");
				result.put("msg", "证书出现错误");
				return result;
			} catch (UnsupportedEncodingException e) {
				// left blank
			}
		} else{
			result.put("status", "200001");
			result.put("msg", "未设置参数");
			return result;
		}
		
		return result;
    }

	@RequestMapping(value="pushAll.do",method = RequestMethod.GET)
	@ResponseBody
    public Map<String, String> pushAll(String msg) {
		Map<String, String> result = new HashMap<String, String>();
		if(StringUtils.isNotBlank(msg)){
			try {
				pushService.push(new String(msg.getBytes("ISO-8859-1")));
				result.put("status", "0");
			} catch (JSONException e) {
				e.printStackTrace();
				result.put("status", "200004");
				result.put("msg", "设置消息格式出错");
				return result;
			} catch (CommunicationException e) {
				e.printStackTrace();
				result.put("status", "200003");
				result.put("msg", "连接苹果服务器出错");
				return result;
			} catch (KeystoreException e) {
				e.printStackTrace();
				result.put("status", "200002");
				result.put("msg", "证书出现错误");
				return result;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else{
			result.put("status", "200001");
			result.put("msg", "未设置参数");
			return result;
		}
		
		return result;
    }
}
